package com.bstek.uflo.form.command;

import java.util.List;

import org.hibernate.Session;

import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.form.model.TableColumn;
import com.bstek.uflo.form.model.TableDefinition;

/**
 * @author Jacky.gao
 * @since 2013年11月5日
 */
public class GetTableDefinitionCommand implements Command<TableDefinition> {
	private long tableId;
	public GetTableDefinitionCommand(long tableId){
		this.tableId=tableId;
	}
	@SuppressWarnings("unchecked")
	public TableDefinition execute(Context context) {
		Session session=context.getSession();
		TableDefinition tableDef=(TableDefinition)session.get(TableDefinition.class, tableId);
		if(tableDef==null)return null;
		tableDef.setColumns(getTableColumns(session,tableId));
		
		List<TableDefinition> slaveTables=session.createQuery("from "+TableDefinition.class.getName()+" where parentId=:parentId").setLong("parentId", tableId).list();
		for(TableDefinition table:slaveTables){
			table.setColumns(getTableColumns(session,table.getId()));
		}
		tableDef.setSlaveTables(slaveTables);
		return tableDef;
	}
	@SuppressWarnings("unchecked")
	private List<TableColumn> getTableColumns(Session session,long tableId) {
		List<TableColumn> cols=session.createQuery("from "+TableColumn.class.getName()+" where tableId=:tableId").setLong("tableId",tableId).list();
		return cols;
	}
}
